// 首先修改顶部的导入部分
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { copyFileSync, mkdirSync, existsSync, createWriteStream } from "fs";
import { resolve } from "path";
import archiver from "archiver";
// 引入dataInfo.json
import dataInfo from "./src/part/dataInfo.json";

const componentName = dataInfo.name;
const outputDir = `dist/${componentName}`;

// 自定义插件，用于复制额外文件
// 修改copyExtraFiles插件，确保不复制public目录下的文件到componentName文件夹
const copyExtraFiles = () => {
  return {
    name: "copy-extra-files",
    closeBundle() {
      const srcDir = resolve(__dirname, "src/part");
      const distDir = resolve(__dirname, "dist");

      if (!existsSync(outputDir)) {
        mkdirSync(outputDir, { recursive: true });
      }

      const filesToCopy = ["dataInfo.json", "publicFun.json", "preview.png"];

      filesToCopy.forEach((file) => {
        const srcPath = resolve(srcDir, file);
        const destPath = resolve(outputDir, file);
        try {
          copyFileSync(srcPath, destPath);
          console.log(`Copied ${file} to ${outputDir} directory`);
        } catch (error) {
          console.error(`Failed to copy ${file}:`, error);
        }
      });

      // 添加压缩逻辑
      try {
        // 创建输出流
        const zipOutput = createWriteStream(
          resolve(distDir, `${componentName}.zip`)
        );
        // 创建archiver实例
        const archive = archiver("zip", { zlib: { level: 9 } });

        // 监听事件
        zipOutput.on("close", () => {
          console.log(
            `Created ${componentName}.zip with size ${archive.pointer()} bytes`
          );
        });

        archive.on("error", (err) => {
          throw err;
        });

        // 管道连接
        archive.pipe(zipOutput);
        // 件到压缩包
        archive.directory(outputDir, false);
        // 完成压缩
        archive.finalize();
      } catch (error) {
        console.error(`Failed to create zip file:`, error);
      }
    },
  };
};

export default defineConfig({
  plugins: [vue(), copyExtraFiles()],
  publicDir: false,
  build: {
    outDir: outputDir,
    emptyOutDir: true,
    lib: {
      entry: {
        [componentName]: resolve(__dirname, "src/part/index.vue"),
        [`${componentName}Attr`]: resolve(__dirname, "src/part/attr.vue"),
      },
      formats: ["umd"],
      fileName: "[name]",
    },
    rollupOptions: {
      external: ["vue", "element-plus", "vant"],
      output: {
        globals: {
          vue: "Vue",
          "element-plus": "ElementPlus",
          vant: "Vant",
        },
      },
    },
  },
});
